package handlers

import (
	"github.com/gin-gonic/gin"
	"novel-mng-sys/cache"
	"novel-mng-sys/models"
	"novel-mng-sys/pkg"
	"strconv"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount == 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次",
		})
		return
	}
	if password != pkg.Md5(password) {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "登录成功",
		})
		return
	}
	if errCount == 2 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,封禁2小时",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var novel models.Novel
	redis_key := "list_" + strconv.Itoa(page)
	jsonData := models.DB.Where("page=?", page).Offset(offset).Debug().Limit(size).Error

	var total int64
	c.JSON(200, gin.H{
		"code":  200,
		"data":  novel,
		"msg":   "success",
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var novel models.Novel
	novel = models.DB.Where("id=?", id)
	c.JSON(200, gin.H{
		"code": 200,
		"data": novel,
		"msg":  "success",
	})
	return
}
